package com.ce.source.analysis.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：xiaopingzhang8@creditease.cn
 * @Description ：CountDownLatch源码分析
 * @ClassName ：CountDownLatchAnalyse
 * @Company ：普信恒业科技发展（北京）有限公司
 * @date ：2017/11/28 16:35
 * <p>
 * CountDownLatch用户主线程等待子线程完成之后，继续执行主线程业务
 * </p>
 */
public class CountDownLatchAnalyse {
    public static void main(String[] args) {
        Long startTime = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch(2);
        final AtomicInteger ThreadNo = new AtomicInteger(1);
        ExecutorService service = Executors.newScheduledThreadPool(10, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                return new Thread(r, "线程" + ThreadNo.getAndIncrement());
            }
        });
        System.out.println("==开启 1 线程");
        Future<Object> future1 = service.submit(new Callable<Object>() {
            public Object call() throws Exception {
                Thread.sleep(10000);
                System.out.println(Thread.currentThread().getName() + " 完成");
                latch.countDown();
                return "xianchen_1";
            }
        });
        System.out.println("==开启 2 线程");
        Future<Object> future2 = service.submit(new Callable<Object>() {
            public Object call() throws Exception {
                Thread.sleep(30000);
                System.out.println(Thread.currentThread().getName() + " 完成");
                latch.countDown();
                return "xianchen_2";
            }
        });
        System.out.println("==开启 3 线程");
        Future<Object> future3 = service.submit(new Callable<Object>() {
            public Object call() throws Exception {
                Thread.sleep(15000);
                System.out.println(Thread.currentThread().getName() + " 完成");
                latch.countDown();
                return "xianchen_3";
            }
        });

        service.shutdown();
        try {
            //主线程等待子线程的完成
            latch.await();
            try {
                System.out.println(future1.get());
                System.out.println(future2.get());
                System.out.println(future3.get());
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println("3个线程都完成了,耗时" + (System.currentTimeMillis() - startTime) / 1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
